/*
	File:	BitmapFont.cpp
	Author:	TJ Ashby
	Class:	SGD
	Purpose:	Draws text from an image
*/

#include "BitmapFont.h"


BitmapFont::BitmapFont(void)
{
	pTM = nullptr;
	imageID = NOID;
}


BitmapFont::~BitmapFont(void)
{
}

bool BitmapFont::Initialize( String FileName,int Width,int Height,int col,int rows,char FirstChar,bool ToUpper )
{
	pTM = TextureManager::getInstance();

	if(imageID == NOID)
		imageID = pTM->LoadTexture(FileName);

	charWidth = Width;
	numRows = rows;
	charHeight = Height;
	numCols = col;
	firstChar = FirstChar;
	toUpper = ToUpper;

	if(imageID == -1)
		return false;

	return true;
}

void BitmapFont::Print( const char* szText,const Vector2 &Position,float Scale /*= 1*/,Color ColorKey /*= 0xFFFFFFFF*/ )
{
	int x = int(Position.x);
	int y = int(Position.y);

	// Keep track of the starting x position (for new lines)
	int colStart = x;

	for(int i = 0;szText[i] != '\0';++i)
	{
		// Get the char out of the string
		char ch = szText[i];

		if(toUpper)
			ch = toupper(ch);

		// Check for white space
		if(ch == ' ')
		{
			// move the x over
			x += int(charWidth*Scale);
			continue;
		}
		else if(ch == '\n')
		{
			y += int(charHeight*Scale);
			x = colStart;
			continue;
		}

		// Calculate the tile id based on the ASCII value
		int id = ch - firstChar;

		// get the source rect
		RECT rect = {  };

		if(id >= 0)
		{
			rect.left = (id%numCols)*charWidth;
			rect.top = (id/numCols)*charHeight;
			rect.right = rect.left + charWidth;
			rect.bottom = rect.top + charHeight;
		}

		// Draw the text
		pTM->Draw(imageID,Vector2((float)x,(float)y),Vector2(),&rect,0,Vector2(Scale,Scale),ColorKey);

		x += int(charWidth * Scale);
	}
}

void BitmapFont::Shutdown()
{
	pTM = nullptr;
}
